<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use App\Handlers\SwitchHandler;
use App\Handlers\MqttHandler;

class SwitchModel extends Model
{
    protected $table = 'xfy_switches';
    // protected $fillable = ['name', 'project_id', 'pid', 'box_id','group_id'];

    const PHASE_TEXT = ['1' => '1P', '3' => '3P'];
    const LEVEL_TEXT = ['1' => '一级', '2' => '二级', '3' => '三级'];

    public function points()
    {
        return $this->hasMany(SwitchPoint::class, 'switch_id');
    }

    public static function getSwitchNumber($machineCode){
        $k = $machineCode.'_*_addr';
        $keys = Redis::keys($k);
        $switchNum = [];
        foreach ($keys as $oneKey) {
            $oneKey = str_replace('laravel_database_', '', $oneKey);
            $one = Redis::get($oneKey);
            $switchNum[intval($one)] = intval($one);
        }
        return $switchNum;
    }

    public static function getSsnByParent($pid, $number){
        $parent = self::find($pid);
        $k = $parent['machine_code'].'_*_addr';
        $keys = Redis::keys($k);
        $tmp = '';
        foreach ($keys as $oneKey) {
            $oneKey = str_replace('laravel_database_', '', $oneKey);
            $one = Redis::get($oneKey);
            if (intval($one) == $number) {
                $tmp = $oneKey;
                break;
            }
        }
        $tmpArr = explode('_', $tmp);
        return $tmpArr[1];
    }

    public static function checkMachineCode($machineCode){
        $k = $machineCode.'_*_addr';
        $keys = Redis::keys($k);
        if (count($keys) > 0) {
            return true;
        } else {
            return false;
        }
    }

    public static function afterDeleted($id){
        $switches = self::where('pid', $id)->get();
        if ($switches) {
            foreach ($switches as $one) {
                DB::table('xfy_switch_points')->where('switch_id', $one['id'])->delete();
                DB::table('xfy_switches_switch_data')->where('switch_id', $one['id'])->delete();
                // DB::table('xfy_switch_electric')->where('switch_id', $one['id'])->delete();
                $one->delete();
            }
        } else {
            DB::table('xfy_switch_points')->where('switch_id', $id)->delete();
            DB::table('xfy_switch_data')->where('switch_id', $id)->delete();
            // DB::table('xfy_switch_electric')->where('switch_id', $id)->delete();
        }
    }

    public static function setSwitchOn($gateway, $switchId, $pn, $ssn){
        $cmd = SwitchHandler::getSwitchCode($pn, $ssn, 1);
        $res = MqttHandler::SendMsgViaMqtt($gateway, $switchId, $cmd, 1);
        return $res;
    }

    public static function setSwitchOff($gateway, $switchId, $pn, $ssn){
        $cmd = SwitchHandler::getSwitchCode($pn, $ssn, 4);
        $res = MqttHandler::SendMsgViaMqtt($gateway, $switchId, $cmd, 0);
        return $res;
    }
}